//
//  GCDSemaphore.m
//  MyFunctionDemo
//
//  Created by Ting Han on 2017/8/28.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "GCDSemaphore.h"

@interface GCDSemaphore ()

@property (strong, nonatomic) dispatch_semaphore_t dispatchSemaphore;

@end
@implementation GCDSemaphore

- (instancetype)init
{
    return [self initWithValue: 1];
}

- (instancetype)initWithValue: (NSUInteger)value
{
    if (self = [super init]) {
        self.dispatchSemaphore = dispatch_semaphore_create(value);
    }
    return self;
}

- (void)wait
{
    dispatch_semaphore_wait(self.dispatchSemaphore, DISPATCH_TIME_FOREVER);
}

- (BOOL)waitWithTimeout: (NSTimeInterval)timeout
{
    return dispatch_semaphore_wait(self.dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC)) == 0;
}

- (BOOL)signal
{
    return dispatch_semaphore_signal(self.dispatchSemaphore) != 0;
}



@end
